//
//  DatabaseManager.m
//  smzdm_lib
//
//  Created by tom on 16/5/19.
//  Copyright © 2016年 sm. All rights reserved.
//

#import "DatabaseManager.h"

static NSString *const kDatabaseFileName = @"smzdm.sqlite" ;

@interface DatabaseManager ()
@property(nonatomic,assign)  BOOL isDataBaseOpened ;

@end

@implementation DatabaseManager

+(void)load {
   [[DatabaseManager defaultManger] openDataBase];

    if ([[DatabaseManager defaultManger] isDataBaseOpened]) {
#ifdef DEBUG
        NSLog(@"打开数据库成功 %@",[[DatabaseManager defaultManger] databasePath]);
#endif
    }
}

+(instancetype)defaultManger {
    static DatabaseManager *manager = nil ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DatabaseManager alloc]init];
    });
    return manager;
}

- (instancetype)init{

    if (self = [super init]) {
        _isDataBaseOpened = NO;
        
            /// 创建数据库
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory = [paths objectAtIndex:0];
        NSString *dbPath = [documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
        _databasePath = dbPath;
        _dataBase = [FMDatabase databaseWithPath:dbPath];
        
            /// 打开数据库
        [self openDataBase];
    }
    return self;
}
- (BOOL)isDataBaseOpened {

  return  _isDataBaseOpened  ;
}

- (void)openDataBase {
    if ([_dataBase open]) {
        _isDataBaseOpened = YES;
    }else{
        _isDataBaseOpened = NO ;
    }
  
}
- (void)closeDataBase {
    BOOL flag = [_dataBase close];
    if (flag ) {
        _isDataBaseOpened = NO;
    }
}

@end
